<template>
  <div class="app-container">
    <el-form :model="param" :inline="true" label-width="68px">
      <el-form-item style="width:240px">
        <div>箱号</div>
        <MultipleBoxNumbersDialog v-model.trim="param.containerNo"/>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>订单号</div>
        <el-input v-model.trim="param.orderNo" placeholder="请输入订单号"> </el-input>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>业务编号</div>
        <el-input v-model.trim="param.businessNo" placeholder="请输入业务编号"> </el-input>
      </el-form-item>
        <el-form-item style="width:240px">
        <div>操作员</div>
        <el-input v-model.trim="param.agentOperatorUserName" placeholder="请输操作员"> </el-input>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>出发城市</div>
        <city-select :selectCity="param.carryCityId" @cityId="startCityId" style="width: 100%;"></city-select>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>到达城市</div>
        <city-select :selectCity="param.returnCityId" @cityId="backCityId" style="width: 100%;"></city-select>
      </el-form-item>
      <el-form-item style="width:300px">
        <div>下单日期</div>
        <el-date-picker v-model="param.createDate" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item style="width:300px">
        <div>预计提箱日期</div>
        <el-date-picker v-model="param.planPickupDate" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item style="width:240px">
        <div>集装箱公司</div>
        <el-input v-model.trim="param.companyName" placeholder="请输入集装箱公司名称"> </el-input>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>联系人</div>
        <el-input v-model.trim="param.boxEastUserName" placeholder="请输入联系人"> </el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleReSet" :icon="Refresh" style="margin-top: 30px">重置</el-button>
        <el-button @click="getTableData" :icon="Search" type="primary" style="margin-top: 30px">查询</el-button>
      </el-form-item>
    </el-form>

    <cz-tages :bottomLine="true" :typeList="typeList" @handleTypeChange="handleTypeChange"
      style="float: left;"></cz-tages>
    <span style="margin-top: -40px;float: right;">
      <el-button :icon="Finished" size="small" @click="deleteBoxAll" plain class="operatingArea">批量删除</el-button>
      <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有订单" placement="left">
        <template v-if="isSelectAll">
          <el-button :icon="Finished" size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
        </template>
        <template v-else>
            <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
        </template>
      </el-tooltip>
      <el-button :icon="Upload" type="primary" size="small" @click="toExportAgentCallbackOrder" plain>导出</el-button>
      <el-button :disabled="param.status != 15" size="small" type="primary" style="width: 80px;" round @click="handlePackingClose" plain>提完</el-button>
    </span>
    <Table ref="tableRef" :allId="allId" :isAllCheck="isAllCheck" v-bind="table" @pageChange="onTablePageChange" @showInfo="showInfo"
      @handleShowContract="handleShowContract" @deleteBox="deleteBox" @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox">
    </Table>

    <!-- dialog -->
    <el-dialog v-model="param.dialogVisible" title="提示" width="500">
      <span>您确认所选订单已提完所需集装箱吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="boxDown">确定</el-button>
          <!-- <el-button type="primary" @click="param.dialogVisible = false">取消</el-button> -->
        </div>
      </template>
    </el-dialog>

    <!-- 订单申请协议 -->
    <el-dialog v-model="param.dialogContract" :with-header="false">
      <pdfViewer :url="param.contractUrl"></pdfViewer>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import pdfViewer from '@/components/pdf'
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
// import { getTable } from '@/api/orderManage/index.ts'
import { getBoxEastSelfTable, getAgentSelfTable, accomplishCallbackOrder,exportAgentCallbackOrder ,deleteIds,agentStatusCount} from '@/api/boxCallBack/order'
// import { getBoxEastSelfTable, exportBoxEastCallbackOrder, getAgentSelfTable, accomplishCallbackOrder,boxEastStatusCount,deleteIds } from '@/api/boxCallBack/order'

import { downloadFile } from '@/utils/download'
import citySelect from '@/components/citySelect'
import orderInfo from '@/store/modules/order'

import { computed, onMounted, onActivated, reactive, ref } from 'vue';
import { Upload, Finished, Document } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router';
import { ElMessage ,ElMessageBox} from 'element-plus'
import MultipleBoxNumbersDialog from '@/components/dialog/multipleBoxNumbersDialog'
import {formatContainerNo} from '@/utils/mlpBox' // 格式化箱号

const router = useRouter();

const param = reactive({
  loading: false,
  dialogVisible:false,
  pageNum: 1,
  pageSize: 10,// 订单状态 5-已下单|待开提箱单 10-待提未付|待提未收 15-已提未付|已提未收 20-待还未付|待还未收 25-待还已付|待还已收 30-已完成 35-已取消
  stateFilter: { 5: '待开提箱单', 10: '待提未付', 15: '已提未付', 20: '未还未付', 25: '未还已付', 30: '已完成', 35: '已取消', 40: '取消中', 2: '待确认', 3: '待审核' },
  // stateColor: { 5: '#22A86D', 10: '#2158F3', 15: '#2158F3' },
  sourceFilter: { 5: '集装箱公司', 10: '客户' },
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '20', label: '混提(次新或者适货)', },
    { value: '5', label: '全新', },
  ],
  beginTotalRentQty: '',
  endTotalRentQty: '',
  returnCityId: '',
  carryCityId: '',
  startCityOptions: [],
  backCityOptions: [],
  companyName:"",
  boxEastUserName:'',
  status:''
});

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'orderNo', colWidth: '220', title: '订单号', type: '<a>', command: 'showInfo', isCheck: true },
    { key: 'businessNo', colWidth: '150', title: '业务编号', type: 'text', isCheck: true },
    { key: 'carryCityName', colWidth: '100', title: '出发城市', type: 'twoRow', isCheck: true },
    { key: 'returnCityString', colWidth: '100', title: '到达城市', type: 'twoRow', isCheck: true },
    { key: 'createTime', colWidth: '170', title: '下单日期', type: 'dateTime', isCheck: true },
    { key: 'planPickupDate', colWidth: '170', title: '预计提箱日期', type: 'date', isCheck: true },
    { key: 'boxType', colWidth: '100', title: '箱型', type: 'filter', filter: { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }, isCheck: true },
    { key: 'boxCondition', colWidth: '100', title: '箱况', type: 'filter', filter: { 5: '全新', 10: '次新', 15: '适货', 20: '混提' }, isCheck: true },
    { key: 'boxUsagePeriod', colWidth: '100', title: '箱使期', type: 'add', after: '天', isCheck: true },
    { key: 'boxQuantity', colWidth: '100', title: '回调箱量', type: 'text', isCheck: true },
    { key: 'amount', colWidth: '120', title: '订单金额', type: 'add', before: '￥',currency:"currency", isCheck: true },
    { key: 'status', colWidth: '100', title: '订单状态', type: 'filter', roleType:'hdHd',filter: param.stateFilter, isCheck: true },
    { key: 'rentSource', colWidth: '100', title: '订单源', type: 'filter', filter: param.sourceFilter, isCheck: true },
    { key: 'boxEastUserName', colWidth: '120', title: '联系人', type: 'text', isCheck: true },
    { key: 'agentOperatorUserName', colWidth: '120', title: '操作员', type: 'text', isCheck: true },

    // { key: 'boxEastUserTel',key2: 'boxEastUserAreaCode', colWidth: '150', title: '联系电话', type: 'mobileCode',isCheck: true },
    // { key: 'orderNo', colWidth: '220', title: '发票号', type: '<a>', command: 'showInfo', isCheck: true },
    {
      key: 'operate',
      colWidth: '120',
      title: '订单申请协议',
      type: 'operate',
      isCheck: true,
      buttons: [
        {
          icon: Document,
          command: 'handleShowContract',
          isShow: (row) => {
            return row.downloadUrl
          },
        },
      ],
    },
    { key: 'companyName', colWidth: '200', title: '集装箱公司', type: 'text', isCheck: true },
         {
      key: 'operate',
      colWidth: '100',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          // content: '删除',
          // icon: 'Delete',
          command: 'deleteBox',
          name:'删除',
          isShow: (row: { status: string; }) => {
            // return row.status != '5';
            return  row.status == '35'
          },
        },

      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
});

const typeList=ref([])

function handleTypeChange(val: any) {
  // console.log(val)
  param.status = val
  getTableData()
  deselectAll()
}

function handlePackingClose() {
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  if (checkAllItem.length == 0) return ElMessage.warning('请选择要完成的订单')
  param.dialogVisible = true
}

function getTableData() {
  const { container, containerList } = formatContainerNo(param.containerNo);
  let data = {
    containerNo: container, // 单箱号查询
    containerNos: containerList, // 多箱号查询
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    companyName:param.companyName,
    orderNo: param.orderNo,
    businessNo: param.businessNo,
    agentOperatorUserName: param.agentOperatorUserName,
    boxEastUserName: param.boxEastUserName,
    carryCityId: param.carryCityId,
    returnCityId: param.returnCityId,
    status: param.status || null
  }
  if (param.createDate) {
    data.beginCreateTime = param.createDate[0]
    data.endCreateTime = param.createDate[1]
  }
  if (param.planPickupDate) {
    data.beginPlanPickupDate = param.planPickupDate[0]
    data.endPlanPickupDate = param.planPickupDate[1]
  }
  table.config.loading = true;
  // 获取列表数据 
  getAgentSelfTable(data).then(res => {
    table.data = res.data.list;
    table.data.forEach((item) => {
      const arry = JSON.parse(item.returnCity)
      // console.log(arry)
      if (arry) {
        item.returnCityString = cityListString(arry)
        item.returnCountryName = arry[0].returnCountryName
      }
    })
    table.config.total = res.data.total;
  });
    agentStatusCount(data).then((res: { data: any }) => {
    const resList = res.data 
    const list = [
    { id: 0, name: '全部', num: 0  },
    { id: 2, name: '待确认' , num: 0 },
    { id: 3, name: '待审核' , num: 0 },
    { id: 5, name: '待开提箱单', num: 0  },
    { id: 10, name: '待提' , num: 0 },
    { id: 15, name: '已提' , num: 0 },
    { id: 20, name: '未还' , num: 0 },
    { id: 25, name: '已还' , num: 0 },
    { id: 30, name: '已完成' , num: 0 },
    { id: 40, name: '待取消' , num: 0 },
    { id: 35, name: '已取消' , num: 0 } 
  ]
    typeList.value = formatStateCount(list, resList)
    table.config.loading = false;
  })
  table.config.loading = false;
}
// 功能函数
const formatStateCount = (stateList: any, resList: any) => {
  let total = 0;
  stateList.forEach(item => {
    resList.forEach((obj: { status: number; totalQty: number }) => {
      if (item.id == obj.status) {
        item.num = obj.totalQty
        total += obj.totalQty
      }
    })
  })
  stateList.map(obj => {
    if (obj.id == 0) {
      obj.num = total
    }
  })
  return stateList
};
//重置
function handleReSet() {
  param.containerNo = ''
  param.containerNos = []
  param.orderNo = null
  param.businessNo = null
  param.agentOperatorUserName = null
  param.boxEastUserName = null
  param.carryCityId = null
  param.returnCityId = null
  param.createDate = null
  param.planPickupDate = null
  param.companyName=null
  getTableData()
}

//分页
function onTablePageChange(page) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

//返回城市，多城市格式化展示
function cityListString(arry: any) {
  let cityListString = ''
  if (!arry) return ''
  arry.map((item: any, index: number) => {
    let dos = index == 0 ? '' : '/'
    cityListString = cityListString + dos + item.returnCityName
  })
  return cityListString
}

//
const tableRef = ref({ multipleSelection: [] })
const selection = computed(() => {
  let ids: any[] = []
  tableRef.value.multipleSelection.map((item: any) => {
    ids.push(item.id)
  })
  return ids
})
const boxDown = () => {
  const ids = selection.value // [1,2]
  accomplishCallbackOrder(ids).then((res: any) => {
    param.dialogVisible=false
    getTableData()
  })
}

const showInfo = (row: any) => {
  router.push({
      path:'agentHuiDiaoOrderInfo',
      query:{
          orderId: row.id
      }
  })
  
}


// 城市id回写
const startCityId = (id: string) => {
  param.carryCityId = id
}
const backCityId = (id: string) => {
  param.returnCityId = id
}


//查看协议
const handleShowContract = (row: any) => {
  param.dialogContract = true
  const downloadUrl = JSON.parse(row.downloadUrl)
  param.contractUrl = downloadUrl.url
}

onActivated(() => {
  getTableData()
})

const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）
const slectAll = async(val:any) =>{
    checkAll.value = []
    let data = {
      pageNum: 1,
      pageSize: 10000,
      status: param.status || ''
    }
    await getAgentSelfTable(data).then(res =>{ 
      if(res.code == "00000" && res.data.list  && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value?.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
//批量删除操作
const deleteBoxAll=()=>{
    let row = selection.value
   if(row.length==0){
      ElMessage.warning('请选择要删除的数据');
        return false
    }
    console.log('row',row)
    deleteBox(row)
}
//删除操作
const deleteBox = (row) => {
  ElMessageBox.confirm(
    '您确定要删除订单吗？',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      let data=[]
      if(row?.id){
        //单独删除
        data.push(row.id)
      }else{
        //批量
        data=row
      }
      deleteIds(data).then((res) => {
        ElMessage.success('删除成功')
        getTableData()
      })
    })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value?.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}

const toExportAgentCallbackOrder = () => { 
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }


  const ids = checkAllItem.map((item: any) => item.id)
  if (ids.length < 1) return ElMessage.warning('请选择要导出的订单！')
    ElMessageBox.confirm('确认要导出选中的订单', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        exportAgentCallbackOrder(ids).then((res: any) => {
              downloadFile(res, '订单列表详情') 
          }).catch((error) => {
              ElMessage.error(error)
          })
      }).catch(() => { });
  } 
</script>